package com.fushenlan.epidemicControl.config;


import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * 获取当前登录人
 */
@Slf4j
@Component
public class JwtUtil {

    private static JwtProvider jwtProvider;

    @Autowired
    public void setJwtProvider(JwtProvider jwtProvider) {
        JwtUtil.jwtProvider = jwtProvider;
    }

    private static HttpServletRequest request;

    @Autowired
    public void setRequest(HttpServletRequest request) {
        this.request = request;
    }

    private static JWTPayload getPayload() {
        String token = jwtProvider.resolveToken(request);
        log.info("token:{}", token);
        String openid = JWTUtil.parseToken(token).getPayload("openid").toString();
        boolean validateToken = jwtProvider.validateToken(token,openid);
        if (!validateToken) {
            throw new RuntimeException("invalid token");
        }
        return JWTUtil.parseToken(token).getPayload();
    }

    /**
     * 获取当前登录人信息
     * @param key
     * @return
     */
    public static String getUserInfo(String key){
        JWTPayload payload = getPayload();
        String info = payload.getClaim(key) + "";
        return info;
    }
}
